package com.sam.library.document;

import android.annotation.SuppressLint;
import android.util.ArraySet;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * @author wanghao
 * @date 2022/11/1.
 * @des
 */
public class StringUtil {

    @SuppressLint("SimpleDateFormat")
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");

    public static String formatFileInfo(File file) {
        if (file.isDirectory()) {
            int childSize = file.listFiles() != null ? file.listFiles().length : 0;
            return formatDate(file.lastModified()) + " - " + childSize + "项";
        } else {
            return formatDate(file.lastModified()) + " - " + formatFileSize(file.length());
        }
    }

    public static String formatDate(long lastModified) {
        return simpleDateFormat.format(new Date(lastModified));
    }

    public static String formatFileSize(long fileSize) {
        DecimalFormat df = new DecimalFormat("#.00");
        if (fileSize == 0) {
            return "0B";
        }

        if (fileSize < 1024) {
            return df.format(fileSize) + "B";
        }
        if (fileSize < 1048576) {
            return df.format(fileSize / 1024f) + "KB";
        }

        if (fileSize < 1073741824) {
            return df.format(fileSize / 1048576f) + "MB";
        }

        return df.format(fileSize / 1073741824f) + "GB";

    }

    public static String formatValue(Object obj) {
        if (obj instanceof Set) {
            return stringSetToString((Set<String>) obj);
        }
        return obj.toString();
    }

    public static String stringSetToString(Set<String> set) {
        JSONArray array = new JSONArray();
        if (set != null && set.size() > 0) {
            for (String item : set) {
                array.put(item);
            }
        }
        return array.toString();
    }

    public static Set<String> stringToStringSet(String setString) {
        Set<String> set = new HashSet<>();
        try {
            JSONArray array = new JSONArray(setString);
            for (int i = 0; i < array.length(); i++) {
                set.add(array.getString(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return set;
    }
}
